package com.gubei.subject.domain.handler.subject;

import com.google.common.base.Preconditions;
import com.gubei.subject.common.enums.IsDeletedFlagEnum;
import com.gubei.subject.common.enums.SubjectInfoTypeEnum;
import com.gubei.subject.domain.convert.MultipleSubjectConverter;
import com.gubei.subject.domain.entity.SubjectAnswerBO;
import com.gubei.subject.domain.entity.SubjectInfoBO;
import com.gubei.subject.domain.entity.SubjectOptionBO;
import com.gubei.subject.infra.basic.entity.SubjectMultiple;
import com.gubei.subject.infra.basic.service.SubjectMultipleService;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 多选题的策略模式
 */
@Component
public class MultipleTypeHandler implements SubjectTypeHandler {

    @Resource
    private SubjectMultipleService subjectMultipleService;

    @Override
    public SubjectInfoTypeEnum getHandlerType() {
        return SubjectInfoTypeEnum.MULTIPLE;
    }

    @Override
    public void add(SubjectInfoBO subjectInfoBO) {
        List<SubjectMultiple> subjectMultipleList = new LinkedList<>();
        Preconditions.checkArgument(!CollectionUtils.isEmpty(subjectInfoBO.getOptionList()),"選択分岐をnullにすることはできません。");
        subjectInfoBO.getOptionList().forEach(option -> {
            SubjectMultiple subjectMultiple = MultipleSubjectConverter.INSTANCE.convertBoToMultipleEntity(option);
            subjectMultiple.setSubjectId(subjectInfoBO.getId());
            subjectMultiple.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
            subjectMultipleList.add(subjectMultiple);
        });

        //Stream流
        List<SubjectMultiple> multipleList = subjectInfoBO.getOptionList().stream().map(option->{
            SubjectMultiple subjectMultiple = MultipleSubjectConverter.INSTANCE.convertBoToMultipleEntity(option);
            subjectMultiple.setSubjectId(subjectInfoBO.getId());
            subjectMultiple.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
            return subjectMultiple;
        }).collect(Collectors.toList());
        subjectMultipleService.batchInsert(multipleList);
    }

    @Override
    public SubjectOptionBO query(Long subjectId) {
        SubjectMultiple subjectMultiple = new SubjectMultiple();
        subjectMultiple.setSubjectId(subjectId);
        List<SubjectMultiple> subjectMultipleList = subjectMultipleService.queryByCondition(subjectMultiple);
        List<SubjectAnswerBO> subjectAnswerBOList = MultipleSubjectConverter.INSTANCE.convertEntityListToBoList(subjectMultipleList);
        SubjectOptionBO subjectOptionBO = new SubjectOptionBO();
        subjectOptionBO.setOptionList(subjectAnswerBOList);
        return subjectOptionBO;
    }
}
